package com.ezjie.ielts.module_word;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.application.YsApplication;
import com.ezjie.ielts.core.base.BaseBean;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.model.CadicatesBean;
import com.ezjie.ielts.model.WordHomeData;
import com.ezjie.ielts.model.WordHomeResponse;
import com.ezjie.ielts.model.WordStudyingData;
import com.ezjie.ielts.model.WordStudyingResponse;
import com.ezjie.ielts.module_word.adapter.WordGroupAdapter;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.DateUtil;
import com.ezjie.ielts.util.DensityUtil;
import com.ezjie.ielts.util.ListUtils;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.util.WordHomeDataUtil;
import com.ezjie.ielts.view.swipemenulistview.SwipeMenu;
import com.ezjie.ielts.view.swipemenulistview.SwipeMenuCreator;
import com.ezjie.ielts.view.swipemenulistview.SwipeMenuItem;
import com.ezjie.ielts.view.swipemenulistview.SwipeMenuListView;
import com.ezjie.ielts.view.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

/**
 * 单词组 生成
 * 
 * @author renyangyang
 *
 */
@ContentView(R.layout.layout_word_group_build)
public class WordGroupBuildActivity extends BaseFragmentActivity {
	private static final String TAG = WordGroupBuildActivity.class.getSimpleName();
	private Context mContext;

	@ViewInject(R.id.navi_back_btn)
	private ImageView navi_back_btn;
	@ViewInject(R.id.navi_title_text)
	private TextView navi_title_text;
	@ViewInject(R.id.btn_start)
	private Button btn_start;// 到第一次学习界面
	@ViewInject(R.id.rl_unknow)
	private RelativeLayout rl_unknow;
	@ViewInject(R.id.rl_know)
	private RelativeLayout rl_know;
	@ViewInject(R.id.tv_unknowNum)
	private TextView tv_unknowNum;
	@ViewInject(R.id.tv_knowNum)
	private TextView tv_knowNum;
	@ViewInject(R.id.lv_unknow)
	private SwipeMenuListView lv_unknow;
	@ViewInject(R.id.lv_know)
	private SwipeMenuListView lv_know;
	@ViewInject(R.id.iv_knowSanjiao)
	private ImageView iv_knowSanjiao;
	@ViewInject(R.id.iv_unknowSanjiao)
	private ImageView iv_unknowSanjiao;
	@ViewInject(R.id.word_group_build_finish_rl)
	private RelativeLayout word_group_build_finish_rl;

	private List<CadicatesBean> allList;// 所有的筛词
	private List<Integer> knownList;// 认识下标的列表
	private List<Integer> unknownList;// 不认识 下标的 列表
	private List<CadicatesBean> knowBeans;// 当前认识的单词队列
	private List<CadicatesBean> unknowBeans;// 当前不认识的单词队列

	private int knownPosition = -1;// 认识字符的位置
	private CadicatesBean knownBean;
	private int unknownPosition = -1;// 不认识字符的位置
	private CadicatesBean unknownBean;

	private WordGroupAdapter knowAdapter;
	private WordGroupAdapter unknowAdapter;
	private boolean unKnowExpand;// 不认识的展开 true，认识的展开为false

	private boolean isExit;// 直接点击返回提交的true 点击开始练习提交的false

	private int[] imgs;
	private static int size;
	private static Random rand = new Random(47);

	private WordTask mWordTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		ViewUtils.inject(this);

		mContext = this;
		knowBeans = new ArrayList<CadicatesBean>();
		unknowBeans = new ArrayList<CadicatesBean>();
		YsApplication application = (YsApplication) getApplication();
		imgs = application.getImgs();
		size = imgs.length;
		mWordTask = new WordTask(this);

		init();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_WORD_GROUP_BUILD);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_WORD_GROUP_BUILD);
	}

	private void init() {

		int img = rand.nextInt(size);

		YsApplication myApplication = (YsApplication) getApplication();
		allList = myApplication.getList();
		knownList = myApplication.getKnownList();
		unknownList = myApplication.getUnknownList();
		// 给列表赋值
		initList();

		rl_unknow.setOnClickListener(this);
		rl_know.setOnClickListener(this);
		if (unknowBeans != null && unknowBeans.size() > 0) {
			// lv_unknow.setVisibility(View.VISIBLE);
			// lv_know.setVisibility(View.GONE);
			unKnowExpand = true;
			tv_unknowNum.setText(unknowBeans.size() + "");
			// iv_unknowSanjiao.setVisibility(View.VISIBLE);
			// iv_knowSanjiao.setVisibility(View.GONE);
		}
		if (knowBeans != null) {
			tv_knowNum.setText(knowBeans.size() + "");
		}

		knowAdapter = new WordGroupAdapter(mContext);
		unknowAdapter = new WordGroupAdapter(mContext);
		knowAdapter.setList(knowBeans);
		unknowAdapter.setList(unknowBeans);

		lv_know.setAdapter(knowAdapter);
		lv_unknow.setAdapter(unknowAdapter);

		navi_back_btn.setOnClickListener(this);
		navi_title_text.setText(R.string.word_filter_title);
		btn_start.setOnClickListener(this);
		word_group_build_finish_rl.setBackgroundResource(imgs[img]);

		// step 1. create a MenuCreator
		SwipeMenuCreator creator1 = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				createKnownMenu(menu);

			}

			private void createKnownMenu(SwipeMenu menu) {
				if (mContext != null) {
					SwipeMenuItem item1 = new SwipeMenuItem(mContext);
					item1.setBackground(new ColorDrawable(Color.rgb(116, 190, 75)));
					item1.setWidth(DensityUtil.dip2px(mContext, 90));
					item1.setTitle("认识");
					item1.setTitleSize(18);
					item1.setTitleColor(Color.WHITE);
					menu.addMenuItem(item1);
				}

			}

		};
		SwipeMenuCreator creator2 = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				createUnKnownMenu(menu);

			}

			private void createUnKnownMenu(SwipeMenu menu) {
				SwipeMenuItem item1 = new SwipeMenuItem(mContext);
				item1.setBackground(new ColorDrawable(Color.rgb(254, 127, 114)));
				item1.setWidth(DensityUtil.dip2px(mContext, 90));
				item1.setTitle("不认识");
				item1.setTitleSize(18);
				item1.setTitleColor(Color.WHITE);
				menu.addMenuItem(item1);

			}

		};
		// set creator
		// lv_unknow.setMenuCreator(creator1);
		// lv_know.setMenuCreator(creator2);

		// step 2. listener item click event
		lv_know.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
				CadicatesBean cadicatesBean = knowBeans.get(position);
				if (allList != null && unknownList != null && knownList != null) {
					// 取出这个bean在 初始list中的位置
					int indexOf = allList.indexOf(cadicatesBean);
					// 把这个位置 从认识列表中删除，加入到不认识列表中
					if (index != -1) {
						Integer object = indexOf;
						knownList.remove(object);
						unknownList.add(object);
						initList();
						knowAdapter.setList(knowBeans);
						unknowAdapter.setList(unknowBeans);
						knowAdapter.notifyDataSetChanged();
						unknowAdapter.notifyDataSetChanged();
						tv_unknowNum.setText(unknowBeans.size() + "");
						tv_knowNum.setText(knowBeans.size() + "");
					}
				}
				return false;
			}
		});
		lv_unknow.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
				CadicatesBean cadicatesBean = unknowBeans.get(position);
				if (allList != null && unknownList != null && knownList != null) {
					// 取出这个bean在 初始list中的位置
					int indexOf = allList.indexOf(cadicatesBean);
					// 把这个位置 从认识列表中删除，加入到不认识列表中
					if (index != -1) {
						Integer object = indexOf;
						unknownList.remove(object);
						knownList.add(object);
						initList();
						knowAdapter.setList(knowBeans);
						unknowAdapter.setList(unknowBeans);
						knowAdapter.notifyDataSetChanged();
						unknowAdapter.notifyDataSetChanged();
						tv_unknowNum.setText(unknowBeans.size() + "");
						tv_knowNum.setText(knowBeans.size() + "");
					}
				}
				return false;
			}
		});

		// 提交，创建单词组
		// submitGroup();
	}

	private void initList() {
		if (allList != null && allList.size() > 0) {
			unknowBeans = new ArrayList<CadicatesBean>();
			knowBeans = new ArrayList<CadicatesBean>();
			if (unknownList != null && unknownList.size() > 0) {
				// 不认识的不为空
				unknownPosition = 0;
				unknownBean = new CadicatesBean();
				unknownBean.setWord("");
				for (int i = 0; i < unknownList.size(); i++) {
					unknowBeans.add(allList.get(unknownList.get(i)));
				}

			}

			knownPosition = unknowBeans.size();
			knownBean = new CadicatesBean();
			knownBean.setWord("");
			if (knownList != null && knownList.size() > 0) {
				// 认识的不为空
				for (int i = 0; i < knownList.size(); i++) {
					knowBeans.add(allList.get(knownList.get(i)));
				}
			}
		}
	}

	private void submitGroup() {
		if (!NetworkUtil.isNetworkAvailable(mContext)) {
			AppUtil.showToast(mContext, R.string.no_network);
			return;
		}

		mWordTask.submitGroup("2", "[" + ListUtils.getWidStrByDouhao(knownList, allList) + "]",
				"[" + ListUtils.getWidStrByDouhao(unknownList, allList) + "]", DateUtil.getLocalTimeZone(),
				new HttpRequestAbstractCallBack(mContext,true) {
					@Override
					public void onStartCallBack() {
						super.onStartCallBack();
						AppUtil.showProgressDialog(mContext);
					}

					@Override
					public void onSuccessCallBack(String result) {
						super.onSuccessCallBack(result);
						LogUtils.d(result);
						AppUtil.dismissProgressDialog();
						try {
							BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
							if (baseBean != null && 200 == baseBean.getStatus_code()) {
								// 提交成功
								// 筛词完成，请求首页接口，刷新天数
								getWordHome();

								WordHomeDataUtil.putTodayStudying(mContext, 1);
								if (unknownList != null) {
									WordHomeDataUtil.putWordStudyingNum(mContext, unknownList.size());
								}
								if (knownList != null) {
									WordHomeDataUtil.putWordMasterNum(mContext, knownList.size());
								}

								if (!isExit) {
									getStudyingWord();
								} else {

									finish();
								}
							} else if (baseBean != null && 208 == baseBean.getStatus_code()) {
								// 有一组正在学习中
								AppUtil.showToast(mContext, R.string.word_filter_summary_studying);
								WordHomeDataUtil.putTodayStudying(mContext, 1);
								finish();
							} else {
								AppUtil.showToast(mContext, R.string.load_net_data_failure);
							}
						} catch (Exception e) {
							LogUtils.d("json数据异常");
							LogUtils.exception(e);
						}
					}

					@Override
					public void onFailureCallBack(HttpException error, String msg) {
						super.onFailureCallBack(error, msg);
						LogUtils.e(msg);
						AppUtil.dismissProgressDialog();

						if (error.getExceptionCode() == 208) {
							AppUtil.showToast(mContext, R.string.word_filter_summary_studying);
							WordHomeDataUtil.putTodayStudying(mContext, 1);
							finish();
						} else {
							AppUtil.showToast(mContext, R.string.load_net_data_failure);
						}
					}
				});

	}

	/**
	 * 获取 词汇首页数据
	 */
	private void getWordHome() {
		if (!NetworkUtil.isNetworkAvailable(mContext)) {
			AppUtil.showToast(mContext, R.string.no_network);
			return;
		}

		mWordTask.getWordHome(DateUtil.getLocalTimeZone(), new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				try {
					WordHomeResponse wordHomeResponse = JSON.parseObject(result, WordHomeResponse.class);
					if (wordHomeResponse != null && 200 == wordHomeResponse.getStatus_code()) {
						String data = wordHomeResponse.getData();
						if (!TextUtils.isEmpty(data)) {
							WordHomeDataUtil.putWordSaveDate(mContext);

							WordHomeData wordHomeData = JSON.parseObject(data, WordHomeData.class);
							int days_future = wordHomeData.days_future;
							WordHomeDataUtil.putWordDaysFuture(mContext, days_future);
						}

					} else {
						if (mContext != null) {
							AppUtil.showToast(mContext, R.string.load_net_data_failure);
						}
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(mContext, R.string.load_net_data_failure);
			}
		});

	}

	private void getStudyingWord() {
		if (!NetworkUtil.isNetworkAvailable(mContext)) {
			AppUtil.showToast(mContext, R.string.no_network);
			return;
		}

		mWordTask.getStudyingWord("simple", new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				try {
					WordStudyingResponse wordStudyingResponse = JSON.parseObject(result, WordStudyingResponse.class);
					if (wordStudyingResponse != null && 200 == wordStudyingResponse.getStatus_code()) {
						String data = wordStudyingResponse.getData();
						if (!TextUtils.isEmpty(data)) {
							WordStudyingData wordStudyingData = JSON.parseObject(data, WordStudyingData.class);
							YsApplication myApplication = (YsApplication) getApplication();
							myApplication.setWordStudyingData(wordStudyingData);
							startActivity(new Intent(mContext, WordStudyManagerActivity.class));
							finish();

						}

					} else {
						AppUtil.showToast(mContext, R.string.load_net_data_failure);
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(mContext, R.string.load_net_data_failure);
			}
		});
	}

	@Override
	public void onBackPressed() {
		if (mContext != null) {

			View view = LayoutInflater.from(mContext).inflate(R.layout.layout_rob_warn_dialog, null);

			final Dialog dialog = new Dialog(mContext, R.style.customDialog);
			dialog.setCanceledOnTouchOutside(true);
			dialog.setContentView(view);
			dialog.show();

			TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
			tv_content.setText(R.string.word_first_study_summary_exit_msg);
			LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
			LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
			ll_layout1.setVisibility(View.VISIBLE);
			ll_layout2.setVisibility(View.GONE);

			Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
			btn_yes.setText(R.string.word_filter_summary_exit_yes);
			Button btn_no = (Button) view.findViewById(R.id.btn_no);
			btn_no.setText(R.string.word_filter_summary_exit_no);
			btn_no.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (mContext != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
						// 友盟统计
						MobclickAgent.onEvent(mContext, "word_screen_finish_cancelBtn");
						finish();

					}
				}
			});
			btn_yes.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (dialog != null && dialog.isShowing()) {
						dialog.cancel();
						// 保存进度
						isExit = true;
						// 友盟统计
						MobclickAgent.onEvent(mContext, "word_screen_finish_saveBtn");
						submitGroup();
					}

				}
			});

		}

	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.navi_back_btn:
			onBackPressed();
			break;
		case R.id.btn_start:
			isExit = false;
			// 先提交 修改后的单词记录
			if (AppUtil.isFastClick()) {
				return;
			}
			//友盟统计
			MobclickAgent.onEvent(this, "word_start_learnBtn");
			LogUtils.d("summer", "点击了");
			submitGroup();
			break;
		case R.id.rl_unknow:
			lv_know.setVisibility(View.GONE);
			lv_unknow.setVisibility(View.VISIBLE);
			iv_unknowSanjiao.setVisibility(View.VISIBLE);
			iv_knowSanjiao.setVisibility(View.GONE);
			break;
		case R.id.rl_know:
			lv_know.setVisibility(View.VISIBLE);
			lv_unknow.setVisibility(View.GONE);
			iv_unknowSanjiao.setVisibility(View.GONE);
			iv_knowSanjiao.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
	}

}
